package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.IntentUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.stark.apkextract.lib.model.AeUtil;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.AppAdapter;
import flc.ast.adapter.FileAdapter;
import flc.ast.bean.MyFileBean;
import flc.ast.databinding.ActivityFileBinding;
import flc.ast.dialog.SortDialog;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.MediaInfo;
import stark.common.basic.media.MediaLoader;
import stark.common.basic.media.bean.AudioBean;
import stark.common.basic.utils.MimeUtils;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.UriUtil;

public class FileActivity extends BaseAc<ActivityFileBinding> {

    public static int type;
    private FileAdapter fileAdapter;
    private AppAdapter appAdapter;
    private List<MyFileBean> listShow = new ArrayList<>();
    private BasePopupView sortPopup;
    private SortDialog sortDialog;
    private int sortBy;
    private boolean isOrder;

    @Override
    protected int onCreate() {
        return R.layout.activity_file;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivFileBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.llPicture.setOnClickListener(this);
        mDataBinding.llVideo.setOnClickListener(this);
        mDataBinding.llDocument.setOnClickListener(this);
        mDataBinding.llAudio.setOnClickListener(this);
        mDataBinding.llApp.setOnClickListener(this);
        mDataBinding.llSortType.setOnClickListener(this);
        mDataBinding.ivSort.setOnClickListener(this);

        mDataBinding.rvFileList.setLayoutManager(new LinearLayoutManager(mContext));
        fileAdapter = new FileAdapter();
        appAdapter = new AppAdapter();
        fileAdapter.setOnItemClickListener(this);
        appAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.llPicture) { //图片
            clearSelection();
            type = 0;
            mDataBinding.tvPicture.setTextColor(Color.parseColor("#181818"));
            mDataBinding.ivPictureSel.setVisibility(View.VISIBLE);
            getImgAndVideoData();
        } else if (id == R.id.llVideo) {    //视频
            clearSelection();
            type = 1;
            mDataBinding.tvVideo.setTextColor(Color.parseColor("#181818"));
            mDataBinding.ivVideoSel.setVisibility(View.VISIBLE);
            getImgAndVideoData();
        } else if (id == R.id.llDocument) { //文档
            clearSelection();
            type = 2;
            mDataBinding.tvDocument.setTextColor(Color.parseColor("#181818"));
            mDataBinding.ivDocumentSel.setVisibility(View.VISIBLE);
            getDocumentData();
        } else if (id == R.id.llAudio) {    //音频
            clearSelection();
            type = 3;
            mDataBinding.tvAudio.setTextColor(Color.parseColor("#181818"));
            mDataBinding.ivAudioSel.setVisibility(View.VISIBLE);
            getAudioData();
        } else if (id == R.id.llApp) {  //应用
            clearSelection();
            type = 4;
            mDataBinding.tvApp.setTextColor(Color.parseColor("#181818"));
            mDataBinding.ivAppSel.setVisibility(View.VISIBLE);
            loadApks();
        } else if (id == R.id.llSortType) { //排序顺序
            isOrder = !isOrder;
            mDataBinding.ivSortType.setImageResource(isOrder ? R.drawable.xxjt : R.drawable.xsjt);
            sortFileBeanList(type == 4 ? appAdapter.getData() : fileAdapter.getData());
        } else if (id == R.id.ivSort) { //排序
            showSortDialog();
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == fileAdapter) {
            String path = fileAdapter.getItem(position).getPath();
            if (MimeUtils.isImgMimeType(path)) {
                Uri imageUri = UriUtil.path2Uri(mContext, path);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(imageUri, "image/*");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivity(intent);
                }
            } else if (MimeUtils.isVideoMimeType(path)) {
                Uri videoUri = UriUtil.path2Uri(mContext, path);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(videoUri, "video/*");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivity(intent);
                }
            } else if (MimeUtils.isAudioMimeType(path)) {
                Uri audioUri = UriUtil.path2Uri(mContext, path);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(audioUri, "audio/*");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivity(intent);
                }
            } else {
                gotoPreviewDoc(UriUtil.path2Uri(mContext, path));
            }
        } else if (adapter == appAdapter) {
            Intent intent = IntentUtils.getLaunchAppDetailsSettingsIntent(appAdapter.getItem(position).getPath());
            try {
                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void initData() {
        mDataBinding.tvSortType.setText(getString(R.string.default_sorting));
        clearSelection();
        if (type == 0) {
            getImgAndVideoData();
            mDataBinding.tvPicture.setTextColor(Color.parseColor("#181818"));
            mDataBinding.ivPictureSel.setVisibility(View.VISIBLE);
        } else if (type == 1) {
            getImgAndVideoData();
            mDataBinding.tvVideo.setTextColor(Color.parseColor("#181818"));
            mDataBinding.ivVideoSel.setVisibility(View.VISIBLE);
        } else if (type == 2) {
            getDocumentData();
            mDataBinding.tvDocument.setTextColor(Color.parseColor("#181818"));
            mDataBinding.ivDocumentSel.setVisibility(View.VISIBLE);
        } else if (type == 3) {
            getAudioData();
            mDataBinding.tvAudio.setTextColor(Color.parseColor("#181818"));
            mDataBinding.ivAudioSel.setVisibility(View.VISIBLE);
        } else if (type == 4) {
            loadApks();
            mDataBinding.tvApp.setTextColor(Color.parseColor("#181818"));
            mDataBinding.ivAppSel.setVisibility(View.VISIBLE);
        }
    }

    //获取视频和图片数据
    private void getImgAndVideoData() {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, type == 0 ? PhotoConfig.Mode.PHOTO : PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                listShow.clear();
                if (selectMediaEntities.size() > 0) {
                    for (SelectMediaEntity selectMediaEntity : selectMediaEntities) {
                        listShow.add(new MyFileBean(selectMediaEntity.getPath(), selectMediaEntity.getMediaName(), selectMediaEntity.getSize(),
                                FileUtils.getFileLastModified(selectMediaEntity.getPath()) / 1000L));
                    }
                    mDataBinding.rvFileList.setAdapter(fileAdapter);
                    fileAdapter.setList(listShow);
                    sortFileBeanList(fileAdapter.getData());
                    mDataBinding.rvFileList.setVisibility(View.VISIBLE);
                    mDataBinding.ivFileNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvFileList.setVisibility(View.GONE);
                    mDataBinding.ivFileNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void getAudioData() {
        RxUtil.create(new RxUtil.Callback<List<AudioBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<AudioBean>> emitter) {
                List<AudioBean> audioBeans = MediaLoader.loadAudio();
                emitter.onNext(audioBeans);
            }

            @Override
            public void accept(List<AudioBean> audioBeanList) {
                listShow.clear();
                if (audioBeanList != null && audioBeanList.size() != 0) {
                    for (AudioBean audioBean : audioBeanList) {
                        listShow.add(new MyFileBean(audioBean.getPath(), audioBean.getName(), audioBean.getSize(),
                                FileUtils.getFileLastModified(audioBean.getPath()) / 1000L));
                    }
                    mDataBinding.rvFileList.setAdapter(fileAdapter);
                    fileAdapter.setList(listShow);
                    sortFileBeanList(fileAdapter.getData());
                    mDataBinding.rvFileList.setVisibility(View.VISIBLE);
                    mDataBinding.ivFileNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvFileList.setVisibility(View.GONE);
                    mDataBinding.ivFileNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    //获取文档数据
    private void getDocumentData() {
        //设置获取的数据类型 只获取pdf
        List<String> type = new ArrayList<>();
        type.add("application/msword");
        type.add("application/vnd.ms-excel");
        type.add("application/vnd.ms-powerpoint");
        type.add("application/pdf");
        type.add("text/plain");
        listShow.clear();
        RxUtil.create(new RxUtil.Callback<List<MediaInfo>>() {
            @Override
            public void doBackground(ObservableEmitter<List<MediaInfo>> emitter) {
                List<MediaInfo> infoList = MediaLoader.loadDoc(type);
                emitter.onNext(infoList);
            }

            @Override
            public void accept(List<MediaInfo> selectMediaEntities) {
                listShow.clear();
                if (selectMediaEntities.size() > 0) {
                    for (MediaInfo bean : selectMediaEntities) {
                        listShow.add(new MyFileBean(bean.getPath(), bean.getName(), bean.getSize(),
                                FileUtils.getFileLastModified(bean.getPath()) / 1000L));
                    }
                }
                if (listShow.size() > 0) {
                    mDataBinding.rvFileList.setAdapter(fileAdapter);
                    fileAdapter.setList(listShow);
                    sortFileBeanList(fileAdapter.getData());
                    mDataBinding.rvFileList.setVisibility(View.VISIBLE);
                    mDataBinding.ivFileNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvFileList.setVisibility(View.GONE);
                    mDataBinding.ivFileNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void loadApks() {
        showDialog(getString(com.stark.common.res.R.string.loading));
        RxUtil.create(new RxUtil.Callback<List<String>>() {
            @Override
            public void doBackground(ObservableEmitter<List<String>> emitter) {
                emitter.onNext(AeUtil.getNoSystemInstalledPackageNames());
            }

            @Override
            public void accept(List<String> packageNames) {
                listShow.clear();
                dismissDialog(500L);
                if (packageNames != null && packageNames.size() > 0) {
                    for (String packageName : packageNames) {
                        listShow.add(new MyFileBean(packageName, AppUtils.getAppName(packageName), FileUtils.getLength(AppUtils.getAppPath(packageName)),
                                FileUtils.getFileLastModified(AppUtils.getAppPath(packageName)) / 1000L));
                    }
                    mDataBinding.rvFileList.setAdapter(appAdapter);
                    mDataBinding.rvFileList.setVisibility(View.VISIBLE);
                    mDataBinding.ivFileNoData.setVisibility(View.GONE);
                    appAdapter.setList(listShow);
                    sortFileBeanList(appAdapter.getData());
                } else {
                    mDataBinding.rvFileList.setVisibility(View.GONE);
                    mDataBinding.ivFileNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void showSortDialog() {
        if (sortDialog == null) sortDialog = new SortDialog(mContext);
        sortPopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(mDataBinding.ivSort).hasShadowBg(false) // 去掉半透明背景
                .asCustom(sortDialog);
        sortDialog.setListener(new SortDialog.Ilistener() {

            @Override
            public void click(int position, String name) {
                sortBy = position;
                mDataBinding.tvSortType.setText(name);
                sortFileBeanList(type == 4 ? appAdapter.getData() : fileAdapter.getData());
            }
        });
        sortPopup.show();
    }

    private void sortFileBeanList(List<MyFileBean> list) {
        switch (sortBy) {
            case 0:
                if (type == 4) {
                    appAdapter.setList(listShow);
                    if (isOrder) {
                        Collections.reverse(appAdapter.getData());
                    }
                } else {
                    fileAdapter.setList(listShow);
                    if (isOrder) {
                        Collections.reverse(fileAdapter.getData());
                    }
                }
                break;
            case 1:
                // 按名称排序
                if (isOrder) {
                    Collections.sort(list, (f1, f2) -> f1.getName().compareToIgnoreCase(f2.getName()));
                } else {
                    Collections.sort(list, (f1, f2) -> f2.getName().compareToIgnoreCase(f1.getName()));
                }
                break;
            case 2:
                // 按时间排序
                if (isOrder) {
                    Collections.sort(list, (f1, f2) -> Long.compare(f1.getDateModified(), f2.getDateModified()));
                } else {
                    Collections.sort(list, (f1, f2) -> Long.compare(f2.getDateModified(), f1.getDateModified()));
                }
                break;
            case 3:
            case 4:
                // 按文件大小排序
                // 按类型排序
                if (isOrder) {
                    Collections.sort(list, (f1, f2) -> Long.compare(f1.getSize(), f2.getSize()));
                } else {
                    Collections.sort(list, (f1, f2) -> Long.compare(f2.getSize(), f1.getSize()));
                }
                break;
            default:
                break;
        }
        fileAdapter.notifyDataSetChanged();
        appAdapter.notifyDataSetChanged();
    }

    //跳转到预览文档应用
    private void gotoPreviewDoc(Uri selUri) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.setType("application/pdf"); // 设置要打开的文档类型（PDF格式）
        List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(intent, 0);
        if (resolveInfos != null && !resolveInfos.isEmpty()) {
            // 设备上至少安装了一个支持打开PDF文档的应用程序
            Intent intent2 = new Intent(Intent.ACTION_VIEW);
            intent2.setData(selUri);
            startActivity(intent2);
        } else {
            // 设备上没有安装任何支持打开PDF文档的应用程序
            ToastUtils.showShort(R.string.no_preview_app);
        }
    }

    private void clearSelection() {
        mDataBinding.tvPicture.setTextColor(Color.parseColor("#59181818"));
        mDataBinding.ivPictureSel.setVisibility(View.INVISIBLE);
        mDataBinding.tvVideo.setTextColor(Color.parseColor("#59181818"));
        mDataBinding.ivVideoSel.setVisibility(View.INVISIBLE);
        mDataBinding.tvDocument.setTextColor(Color.parseColor("#59181818"));
        mDataBinding.ivDocumentSel.setVisibility(View.INVISIBLE);
        mDataBinding.tvAudio.setTextColor(Color.parseColor("#59181818"));
        mDataBinding.ivAudioSel.setVisibility(View.INVISIBLE);
        mDataBinding.tvApp.setTextColor(Color.parseColor("#59181818"));
        mDataBinding.ivAppSel.setVisibility(View.INVISIBLE);
    }

}